﻿using System;

namespace ZCommon;

public static class Singleton<T> where T : class
{
    // 构造函数实例
    private static Lazy<T>? _instance;

    // 参数化实例锁
    private static readonly object _paramLock = new();

    /// <summary>
    /// 使用参数初始化单例（线程安全）
    /// </summary>
    public static T Generate(params object[] args)
    {
        if (_instance == null)
        {
            lock (_paramLock)
            {
                _instance ??= new((Activator.CreateInstance(typeof(T), args) as T)!);
            }
        }

        return _instance.Value;
    }

    /// <summary>
    /// 获取当前活动实例（优先返回参数化实例）
    /// </summary>
    public static T Instance() => _instance!.Value;
}